package com.mulanweb.handler;

import com.jfinal.handler.Handler;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.TableMapping;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by hcy on 2016/4/11.
 */
public class AuthorizationHandler extends Handler {

    @Override
    public void handle(String target, HttpServletRequest req, HttpServletResponse resp, boolean[] isHandled) {
        String auth = req.getHeader("Authorization");
        /*if (StringUtils.isBlank(auth) || isNotExists(auth)) {
            notLoginHandler(resp);
            isHandled[0] = true;
        } else {
            super.next.handle(target, req, resp, isHandled);
        }*/
    }

    /**
     * 判断编码的令牌是否有效
     *
     * @param encryptedToken 编码过的令牌
     * @return 如果编码过的令牌存在，返回true，否则返回false
     */
    /*private boolean isNotExists(String encryptedToken) {
        String sql = "SELECT * FROM " + TableMapping.me().getTable(MAdminLogon.class).getName() + " WHERE EncryptedToken = ?";
        List<MAdminLogon> records = MAdminLogon.dao.findByCache(BasicCacheNames.AdminLogon.FIND_BY_ENCRYPTED_TOKEN, encryptedToken, sql, encryptedToken);
        return CollectionUtils.isEmpty(records);
    }*/

    /**
     * 没有登录处理
     *
     * @param resp 响应信息
     */
    private void notLoginHandler(HttpServletResponse resp) {
        PrintWriter pw = null;
        Ret errorMessage = Ret.create("ReturnCode", 1).put("AlertMessage", "not login");
        try {
            resp.setStatus(200);
            pw = resp.getWriter();
            pw.append(JsonKit.toJson(errorMessage.getData()));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != pw) {
                pw.flush();
                pw.close();
            }
        }
    }

}
